<template>
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="出库仓库">
          <el-select v-model="searchParam.warehouseId" placeholder="请选择" clearable style="width: 200px"
                     @change="searchWareChange">
            <el-option v-for="item in wareList" :key="item.id" :label="item.warehouseName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="出库库位">
          <el-select v-model="searchParam.storageId" placeholder="请选择" clearable style="width: 200px"
                     :disabled="!searchParam.warehouseId">
            <el-option v-for="item in searchStorageList" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>列表信息</div>
        </div>
        <div class="pageTableButView">
          <el-button @click="handleAdd" :icon="Plus">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="calc(100vh - 320px)" row-key="id" :stripe="false" ref="tableRef"
                header-cell-class-name="witheTableHeader" @expand-change="handleExpandChange">
        <el-table-column type="expand">
          <template #default="scope">
            <!-- 子级列表 -->
            <div m="4">
              <el-table ref="tableCil" :stripe="false" border size="small" :data="scope.row.children"
                        style="width: 95%;margin-left: 20px" header-cell-class-name="blueTableHeader"
                        @selection-change="(e)=>{handleSelectionChange(e,scope.row)}">
                <el-table-column type="index" width="80" label="" align="center"/>
                <el-table-column label="物料编码" prop="materialNo" width="300" align="center"
                                 show-overflow-tooltip/>
                <el-table-column label="物料名称" prop="materialName" width="300" align="center"
                                 show-overflow-tooltip/>
                <el-table-column type label="需求数量" prop="count" width="250" align="center"
                                 show-overflow-tooltip/>
                <el-table-column type label="出库数量" prop="" width="250" align="center"
                                 show-overflow-tooltip>
                  <template #default="scopes">
                    <div v-if="scope.row.activate">
                      {{ scopes.row.count }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="100">
          <template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="领用单号" prop="no" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="领用部门" prop="organizationName" min-width="150" show-overflow-tooltip
                         align="center"/>
        <el-table-column label="领用人" prop="receiveUserName" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="出库仓库" prop="warehouseName" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="出库库位" prop="storageName" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="领用设备" prop="equipmentCode" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column type label="状态" prop="" min-width="150"
                         align="center" show-overflow-tooltip>
          <template #default="scope">
            <div v-if="scope.row.activate">已完成</div>
            <div v-else>新建</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="250" show-overflow-tooltip align="center"/>
        <el-table-column label="创建时间" prop="createTime" min-width="250" show-overflow-tooltip align="center"/>
        <el-table-column label="创建人" prop="createUserName" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="操作" min-width="120" align="center" fixed="right">
          <template #default="scopes">
            <el-button type="text" size="small" :icon="Files" @click="handleParentOutIn(scopes.row)">出库</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
                       :current-page="currentPage" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle + '领用 '" width="1200px">
      <el-form ref="formRef" :model="formData" label-width="100px" :rules="outInRules">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="领用部门" style="width:100%" prop="organizationId">
              <el-tree-select v-model="formData.organizationId" :data="workRoomList" check-strictly
                              :props="{ children: 'sonList', label: 'orgName', value: 'id' }"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="领用人" style="width: 250px" required>
              <el-select v-model="formData.receiveUser" placeholder="请选择人员" clearable filterable>
                <el-option v-for="item in teamPeopleData" :key="item.id" :label="item.nickname"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库仓库">
              <el-tree-select v-model="formData.warehouseId" :data="wareList" check-strictly
                              :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="formWareChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库库位" prop="storageId">
              <el-select v-model="formData.storageId" placeholder="请选择" clearable filterable
                         style="width: 400px" :disabled="!formData.warehouseId" @change="storageIdChange">
                <el-option v-for="item in formStorageList" :key="item.id" :label="item.storageName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="领用设备" prop="equipmentId">
              <el-select v-model="formData.equipmentId" placeholder="请选择领用设备" clearable filterable
                         style="width: 400px">
                <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentCode"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="18">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" style="width: 700px" :rows="3" type="textarea"
                        placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.childrenList" style="width:100% " height="300px">
            <el-table-column label="序号" type="index" align="center" width="80"/>
            <el-table-column prop="materialId" label="物料编码" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder=""
                           clearable filterable>
                  <el-option v-for="item in materiaList" :key="item.id" :label="item.materialNo"
                             :value="item.materialId"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="数量" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.count" type="number" :disabled="popType == 1"
                          placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
              <template #header>
                <el-button :icon="Plus" text @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <el-button type="danger" text :icon="Delete" @click="handleConfigDelete(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(formRef)">保存</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, ref, nextTick} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Files, Plus, Refresh, Search} from '@element-plus/icons-vue';

const teamPeopleData = ref([])
const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const wareList = ref([]);
const searchStorageList = ref([]); // 搜索条件的库位列表
const formStorageList = ref([]); // 表单中的库位列表
const tableRef = ref(); // 表格引用

const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

const selectable = (row) => {
  if (row.type == 1) {
    return false;
  }
  return true;
};

const formatType = (row, column, cellValue) => {
  const typeMap = {
    0: '新建',
    1: '入库',
    2: '出库',
    3: '完结'
  };
  return typeMap[cellValue] || '';
};

const formData = ref({
  planNo: '',
  name: '',
  planBeginTime: null,
  planEndTime: null,
  actualBeginTime: null,
  actualEndTime: null,
  organizationId: '',
  status: '0',
  type: '0'
});

const crudTitle = computed(() => {
  if (popType.value === 1) {
    return '查看';
  } else {
    return isEdit.value ? '编辑' : '新建';
  }
});

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  searchStorageList.value = [];
  currentPage.value = 1;
  getList();
};
const equipmentData = ref([]);
const storageList = ref([]);
const materiaList = ref([]);
const formRef = ref();
const outInRules = reactive<FormRules<FormInstance>>({
  organizationId: [
    {required: true, message: '请选择工厂/车间', trigger: 'blur'}
  ],
  receiveUser: [
    {required: true, message: '请输入领用人', trigger: 'blur'}
  ],
  storageId: [
    {required: true, message: '请选择出库仓库', trigger: 'blur'}
  ]
});

const handleAddConfigLine = () => {
  formData.value.childrenList.push({
    materialId: null,
    materialCount: null,
    batchNo: null,
    type: 2
  });
};

// 搜索条件仓库变化
const searchWareChange = (warehouseId) => {
  if (!warehouseId) {
    searchStorageList.value = [];
    searchParam.value.storageId = undefined;
    return;
  }

  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: warehouseId,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        searchStorageList.value = res.data.records;
        // 如果当前选中的库位不在新列表中，则清空
        if (searchParam.value.storageId && !searchStorageList.value.some(item => item.id === searchParam.value.storageId)) {
          searchParam.value.storageId = undefined;
        }
      });
};

const storageIdChange = (warehouseId) => {
  axiosInstance.post('/api/SparePartLog/getPage', {
    storageId: warehouseId,
    current: 1,
    pageSize: 99999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        materiaList.value = res.data.records;
      });
}

// 表单仓库变化
const formWareChange = (warehouseId) => {
  if (!warehouseId) {
    formStorageList.value = [];
    formData.value.storageId = undefined;
    return;
  }

  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: warehouseId,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        formStorageList.value = res.data.records;
        // 如果当前选中的库位不在新列表中，则清空
        if (formData.value.storageId && !formStorageList.value.some(item => item.id === formData.value.storageId)) {
          formData.value.storageId = undefined;
        }
      });
};

const handleSelectionChange = (e, row) => {
  const dataPage = paginatedData.value.map(item => {
    if (item.id === row.id) {
      return {...item, childCheck: e};
    }
    return item;
  });
  paginatedData.value = dataPage;
};

// 处理父级领用按钮点击 - 优化版
const handleParentOutIn = async (row) => {
  try {
    // 1. 先查询最新的子级数据
    const res = await axiosInstance.post('/api/sparePartDetail/getAll', {sparePartId: row.id});
    if (res.code !== 200) {
      ElMessage.warning(res.message || '获取子级数据失败');
      return;
    }

    // 2. 更新当前行的子级数据
    const updatedData = paginatedData.value.map(item => {
      if (item.id === row.id) {
        return {...item, children: res.data};
      }
      return item;
    });
    paginatedData.value = updatedData;

    // 3. 确保子级数据存在
    if (!res.data || res.data.length === 0) {
      ElMessage.warning('该记录没有可出库的物料');
      return;
    }

    // 4. 构造领用参数
    const checkItem = res.data.map(item => ({
      id: item.id,
      type: 3,
      count: item.count
    }));

    // 5. 确认领用
    await ElMessageBox.confirm(
        '是否出库该记录的所有物料？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 6. 执行领用操作
    const result = await axiosInstance.post('/api/sparePartDetail/updateTypeBatch', checkItem);
    if (result.code !== 200) {
      ElMessage.error(result.message || '出库失败');
      return;
    }

    ElMessage.success('出库成功');

    // 7. 关闭所有展开行并刷新列表
    await nextTick();
    paginatedData.value.forEach(item => {
      tableRef.value && tableRef.value.toggleRowExpansion(item, false);
    });

    // 8. 刷新列表数据
    await getList();
  } catch (error) {
    // 用户取消了确认对话框
    if (error !== 'cancel') {
      console.error('领用错误:', error);
    }
  }
};

const handleConfigDelete = (e) => {
  formData.value.childrenList.splice(e, 1);
};

const workRoomList = ref([]); // 车间
const supplierList = ref([]);

const getOption = () => {
  axiosInstance.post('/api/basedataEquipment/getAll', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    equipmentData.value = res.data;
  });
  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
  axiosInstance.post('/api/basedataUser/getPage', {
    "current": 1,
    "pageSize": 99999
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        teamPeopleData.value = res.data.records;
      });
  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

// 新建记录
const handleAdd = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  popType.value = 0;
  isEdit.value = false;
  formData.value = {
    childrenList: [{
      materialId: null,
      materialCount: null,
      batchNo: null,
      type: 2
    }]
  };
  showCrud.value = true;
};

const popType = ref(0); // 0 编辑 1 只读

// 保存记录
const handleSave = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      const param = {
        ...formData.value,
        status: 2,
      };
      axiosInstance.post('/api/sparePart/save', param)
          .then((res) => {
            if (res.code !== 200) {
              ElMessage.error(res.message);
              return false;
            }
            showCrud.value = false;
            getList();
          });
    }
  });
};

const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    // 展开时加载子数据
    rowChildren(row);
  }
};

// 查询子级数据
const rowChildren = (row: any) => {
  axiosInstance.post('/api/sparePartDetail/getAll', {sparePartId: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const listGroup = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return {...item, children: res.data};
      }
      return item;
    });
    paginatedData.value = listGroup;
  });
};

const pageTotal = ref(0);

// 获取列表
const getList = async () => {
  paginatedData.value = [];
  axiosInstance.post('/api/sparePart/getPage', {
    ...searchParam.value,
    current: currentPage.value,
    pageSize: pageSize.value,
    status: 2,
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records.map((item) => ({
          ...item,
          children: [],
          layer: 1,
          _loading: false
        }));
        pageTotal.value = res.data.total;
      });
};

onMounted(() => {
  getList();
  getOption();
});
</script>

<style scoped lang="scss"></style>